package com.xfapp.demos.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfapp.demos.common.Result;
import com.xfapp.demos.entity.Collection;
import com.xfapp.demos.entity.Question;
import com.xfapp.demos.service.ICollectionService;
import com.xfapp.demos.service.IQuestionService;
import javax.annotation.Resource;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 * 存储用户收藏题目的表 前端控制器
 * </p>
 *
 * @author jinYi
 * @since 2025-06-10
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {
    @Resource
    private ICollectionService collectionService;

    @Resource
    private IQuestionService questionService;

    /**
     * 保存或者修改文件
     * @param collections
     * @return
     */
    @PostMapping("/save")
    public Result saveData(@RequestBody List<Collection> collections){
        boolean result = collectionService.saveOrUpdate(collections);
        if (result) {
            return Result.success();
        } else {
            return Result.error("-1", "保存失败");
        }
    }
    /**
     * 删除收藏题目（加删除，未使用）
     */
    @DeleteMapping("/delete")
    public Result deleteDate(@RequestBody Collection collection){
        collection.setDelFlag(1);
        QueryWrapper<Collection> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",collection.getUserId()).eq("question_id",collection.getQuestionId());
        boolean updateResult = collectionService.update(collection,queryWrapper);
        if (updateResult) {
            return Result.success();
        } else {
            return Result.error("-1", "删除失败");
        }
    }
    @GetMapping("/find/{userId}")
    public Result find(@PathVariable Long userId){
        QueryWrapper<Collection> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId).eq("del_flag",0);
        List<Collection> collections = collectionService.list(queryWrapper);
        if (collections.size() == 0) {
            return Result.error("-1", "没有收藏题目");
        }
        return Result.success(collections);
    }
    /**
     * 查询收藏题目（按用户的id）,联表查询对应的题目集合
     */
    @GetMapping("/findQuestion/{userId}")
    public Result findData(@PathVariable Long userId){
        QueryWrapper<Collection> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId).eq("del_flag",0);
        List<Collection> collections = collectionService.list(queryWrapper);
        if (collections.size() == 0) {
            return Result.error("-1", "没有收藏题目");
        }
        List<Long> questionId = collections.stream().map(Collection::getQuestionId).toList();
        List<Question> questionIdList = questionService.listByIds(questionId);
        return Result.success(questionIdList);
    }

}
